//
//  NoteDAO.m
//  Persistence
//
//  Created by 郑火 on 16/2/9.
//  Copyright © 2016年 zwz. All rights reserved.
//

#import "NoteDAO.h"
#import "MKNetworkKit.h"
#import "NSNumber+ErrorMessage.h"
@implementation NoteDAO
static NoteDAO* sharedManager = nil;
+(NoteDAO*) sharedManager
{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        sharedManager = [[self alloc]init];
        [sharedManager managedObjectContext];
    });
    return sharedManager;
}

-(void)create:(Note*)model
{
    MKNetworkHost *host = [[MKNetworkHost alloc]initWithHostName:HOST_NAME];
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    
    param[@"email"]  = USER_ID;
    param[@"type"]  = @"JSON";
    param[@"action"]  = @"add";
    param[@"date"]  = model.date;
    param[@"content"]  = model.content;
    
    MKNetworkRequest* request = [host requestWithPath:HOST_PATH params:param];
    
    [request addCompletionHandler:^(MKNetworkRequest* request){
        NSData *data  = [request responseData];
        NSString * jsonStr = [request responseAsString];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];        NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSNumber *resultCodeNumber = resDict[@"ResultCode"];
        NSInteger resultCode = [resultCodeNumber integerValue];
        if(resultCode >= 0)
        {
            [self.delegate createFinished];
        }
        else
        {
            NSString *Message = [resultCodeNumber errorMessage];
            NSDictionary *userInfo = [NSDictionary dictionaryWithObject:Message forKey:NSLocalizedDescriptionKey];
            NSError *err = [NSError errorWithDomain:@"DAO" code:resultCode userInfo:userInfo];
            [self.delegate createFailed:err];
        }
    } ];
    [host startRequest:request];
    
}

-(void)remove:(Note*)model
{
    
    MKNetworkHost *host = [[MKNetworkHost alloc]initWithHostName:HOST_NAME];
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    
    param[@"email"] = USER_ID;
    param[@"type"]  = @"JSON";
    param[@"action"]  = @"remove";
    param[@"id"]  = model.ID;
    
    MKNetworkRequest *request = [host requestWithPath:HOST_PATH params:param];
    
    [request addCompletionHandler:^(MKNetworkRequest* request){
        NSData *data  = [request responseData];
        NSString * jsonStr = [request responseAsString];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSNumber * resultCodeNum = dict[@"ResultCode"];
        NSInteger resultCode = [resultCodeNum integerValue];
        
        if(resultCode >= 0)
        {
            [self.delegate deleteFinished];
        }
        else
        {
            NSString * msg = [resultCodeNum errorMessage];
            NSDictionary *userInfo = [NSDictionary dictionaryWithObject:msg forKey:NSLocalizedDescriptionKey];
            NSError *error = [[NSError alloc]initWithDomain:@"DAO" code:resultCode userInfo:userInfo];
            [self.delegate deleteFailed:error];
        }
        
    }];
    [host startRequest:request];

}
-(void)modify:(Note*)model
{
    MKNetworkHost * host = [[MKNetworkHost alloc]initWithHostName:HOST_NAME];
    
    NSMutableDictionary * param = [[NSMutableDictionary alloc]init];
    
    param[@"email"] = USER_ID;
    param[@"type"]  = @"JSON";
    param[@"action"]  = @"modify";
    param[@"id"]  = model.ID;
    param[@"date"]  = model.date;
    param[@"content"]  = model.content;
    
    MKNetworkRequest *request = [host requestWithPath:HOST_PATH params:param];
    
    [request addCompletionHandler:^(MKNetworkRequest *request){
        NSData *data  = [request responseData];
        NSString * jsonStr = [request responseAsString];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
//        NSMutableDictionary *dict = [NSJSONSerialization dataWithJSONObject:data options:NSJSONReadingAllowFragments error:nil];
                NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSNumber * resultCodeNum = dict[@"ResultCode"];
        NSInteger  resultCode = [resultCodeNum integerValue];
        if(resultCode >= 0)
        {
            [self.delegate modifyFinished];
        }
        else
        {
            NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[resultCodeNum errorMessage] forKey:NSLocalizedDescriptionKey];
            NSError * err = [NSError errorWithDomain:@"DAO" code:resultCode userInfo:userInfo];
            [self.delegate modifyFailed:err];
        }
    }];
    [host startRequest:request];
}
-(void)findAll
{
    MKNetworkHost *host = [[MKNetworkHost alloc]initWithHostName:HOST_NAME];
    NSMutableDictionary * param = [[NSMutableDictionary alloc]init];
    //param[@"email"] = USER_ID;
    [param setObject:USER_ID forKey:@"email"];
    [param setObject:@"JSON" forKey:@"type"];
    [param setObject:@"query" forKey:@"action"];
    
    MKNetworkRequest * request = [host requestWithPath:HOST_PATH params:param];
    [request addCompletionHandler:^(MKNetworkRequest * request){
        NSData *data  = [request responseData];
        NSString * jsonStr = [request responseAsString];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error  = [[NSError alloc]init];
        NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

        //NSLog(@"data.l = %d",data.length);
        NSLog(@"JSON = %@",jsonStr);
        //NSMutableDictionary *dict = [request responseAsJSON];
        id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if(jsonObject != nil)
            NSLog(@"not nil");
        NSLog(@"dictcount = %d",dict.allKeys.count);
        NSNumber * resultCodeNum = dict[@"ResultCode"];
        NSInteger  resultCode = [resultCodeNum integerValue];
        if(resultCode >= 0)
        {
            NSMutableArray *listDict = dict[@"Record"];
            
            NSMutableArray *reslistData = [NSMutableArray new];
            
            for(NSMutableDictionary * dic in listDict)
            {
                Note* note = [[Note alloc]initWithDate:dic[@"CDate"] content:dic[@"Content"]];
                note.ID = dic[@"ID"];
                [reslistData addObject:note];
                
            }
            [self.delegate findAllFinished:reslistData];
        }
        else
        {
            NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[resultCodeNum errorMessage] forKey:NSLocalizedDescriptionKey];
            NSError * err = [NSError errorWithDomain:@"DAO" code:resultCode userInfo:userInfo];
            [self.delegate findAllFailed:err];
        }

    }];
    
    [host startRequest:request];
}
-(void)findById:(Note*)model
{
    
}


/*  CoreDataBak
-(int)create:(Note*)model
{
    
    NSManagedObjectContext * managerObjectContext = [self managedObjectContext];
    
    NoteManagedObject *note = [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:managerObjectContext];
    [note setValue:model.date forKey:@"date"];
    note.content = model.content;
    
    NSError *error = nil;
    if([managerObjectContext hasChanges] && ![managerObjectContext save:&error])
    {
        NSLog(@"插入数据失败：%@, %@", error, [error userInfo]);
        return -1;
        
    }
    return 0;
}

-(int)remove:(Note*)mocel
{
   
    NSManagedObjectContext * managerObjectContext = [self managedObjectContext];
    NSEntityDescription * entityDescription = [NSEntityDescription entityForName:@"Note" inManagedObjectContext:managerObjectContext];
    //NoteManagerObject *note = [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:managerObjectContext];
    NSFetchRequest * request = [[NSFetchRequest alloc]init];
    [request setEntity:entityDescription];
    
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"date = %@", mocel.date];
    
    [request setPredicate:predicate];
    
    NSError *error = nil;
    NSArray *listData = [managerObjectContext executeFetchRequest:request error:&error];
    
    if(listData.count > 0)
    {
        NoteManagedObject *tmp = [listData lastObject];
        [managerObjectContext deleteObject:tmp];
        error = nil;
        if([managerObjectContext hasChanges]&&![managerObjectContext save:&error])
        {
            NSLog(@"删除失败:%@, %@",error, [error userInfo]);
            return  -1;
        }
    }
    return 0;

}
-(int)modify:(Note*)model
{
    
    NSManagedObjectContext * managerObjectContext = [self managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Note" inManagedObjectContext:managerObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    request.entity = entity;
    request.predicate = [NSPredicate predicateWithFormat:@"date = %@", model.date];
    
    NSError *error = nil;
    NSArray * listData = [managerObjectContext executeFetchRequest:request error:&error];
    if(listData.count > 0)
    {
        NoteManagedObject * tmp = listData.lastObject;
        tmp.content = model.content;
        error = nil;
        if([managerObjectContext hasChanges]&&[managerObjectContext save:&error])
        
        {
            NSLog(@"修改错误:%@,%@", error,[error userInfo]);
            return -1;
        }
        
    }
    return 0;
    
}
-(NSMutableArray*)findAll
{
    NSManagedObjectContext * managerObjectContext = [self managedObjectContext];
    //NSEntityDescription * entityDescription = [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:managerObjectContext];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Note" inManagedObjectContext:managerObjectContext];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    fetchRequest.entity = entity;
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"date" ascending:YES];
    NSArray * sorts = @[sortDescriptor];
    fetchRequest.sortDescriptors = sorts;
    NSError *error = nil;
    
    NSArray *listData = [managerObjectContext executeFetchRequest:fetchRequest error:&error];
    NSMutableArray * resListData  = [[NSMutableArray alloc]init];
    for(NoteManagedObject* tmp in listData)
    {
        Note * note = [Note alloc];
        note.content = tmp.content;
        note.date = tmp.date;
        
        [resListData addObject:note];
    }
    return resListData;

}
-(Note*)findById:(Note*)model
{
    NSManagedObjectContext * managerObjectContext = [self managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Note" inManagedObjectContext:managerObjectContext];
    //NoteManagerObject *note = [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:managerObjectContext];
    NSFetchRequest* fecthRequest = [[NSFetchRequest alloc]init];
    fecthRequest.entity = entity;
    fecthRequest.predicate = [NSPredicate predicateWithFormat:@"date = %@", model.date];
    
    NSError * error = nil;
    NSArray *listData = [managerObjectContext executeFetchRequest:fecthRequest error:&error];
    if(listData.count > 0)
    {
        NoteManagedObject *mo = [listData lastObject];
        Note *note = [Note alloc];
        note.content = mo.content;
        note.date = mo.date;
        return note;
    }
    return nil;
    
}
 */

@end
